package Admin

import (
	m "git.oschina.net/liukexing/RbacManager/models/center"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/utils/pagination"
	"strconv"
)

type UserController struct {
	CommonController
}

func (r *UserController) NestPrepare() {
	group := "Admin"
	controller, action := r.GetControllerAndAction()
	for _, node := range r.nodes {
		if node["Name"].(string) == (group + "." + controller + "." + action) {
			r.Data["Subid"] = node["Id"]
			r.Data["Menuid"] = node["Pid"]
		}
	}
	var Submenu []orm.Params
	for _, node := range r.nodes {
		if node["Level"].(int64) == 2 && node["Pid"].(int64) == r.Data["Menuid"].(int64) {
			Submenu = append(Submenu, node)
		}
	}
	r.Data["Submenu"] = Submenu
	r.Data["Title"] = "后台管理-用户管理"
}

func (r *UserController) URLMapping() {
	r.Mapping("Index", r.Index)
	r.Mapping("UserList", r.UserList)
	r.Mapping("AddUser", r.AddUser)
	r.Mapping("UpdateUser", r.UpdateUser)
	r.Mapping("DelUser", r.DelUser)
	r.Mapping("GetUser", r.GetUser)
	r.Mapping("RoleList", r.RoleList)
	r.Mapping("UpdateRole", r.UpdateRole)
	r.Mapping("DelRole", r.DelRole)
	r.Mapping("AddRole", r.AddRole)
	r.Mapping("GetRole", r.GetRole)
	r.Mapping("UserAccess", r.UserAccess)
	r.Mapping("AddRoleUser", r.AddRoleUser)
	r.Mapping("DelRoleUser", r.DelRoleUser)
	r.Mapping("RoleAccess", r.RoleAccess)
	r.Mapping("AddRoleNode", r.AddRoleNode)
	r.Mapping("DelRoleNode", r.DelRoleNode)
}

// @router /user/index [get]
func (r *UserController) Index() {
	r.Redirect(r.URLFor("Admin.UserController.UserList"), 302)
}

// @router /user/userlist [get]
func (r *UserController) UserList() {
	keyword := r.GetString("keyword")
	sort := r.GetString("sort")
	page, err := r.GetInt64("p")
	cond := orm.NewCondition()
	var cond1 *orm.Condition
	if keyword != "" {
		cond1 = cond.Or("Username__contains", keyword).Or("Nickname__contains", keyword)
	}
	if err != nil {
		page = 1
	}
	if sort == "" {
		sort = "id"
	}
	griddate, count := m.Getuserlist(page, 10, sort, cond1)
	pagination.SetPaginator(r.Ctx, 10, count)
	r.Data["griddate"] = griddate
	r.Data["search"] = keyword
	r.Data["sort"] = sort
}

// @router /user/adduser [post]
func (r *UserController) AddUser() {
	flash := beego.NewFlash()
	result := true
	u := m.User{}
	if err := r.ParseForm(&u); err != nil {
		flash.Error(err.Error())
		result = false
	}
	u.Password = "888888"
	if _, err := m.AddUser(&u); err != nil {
		flash.Error(err.Error())
		result = false
	}
	if result {
		flash.Success("用户添加成功！")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.UserList"), 302)
}

// @router /user/updateuser [post]
func (r *UserController) UpdateUser() {
	flash := beego.NewFlash()
	result := true
	u := m.User{}
	if err := r.ParseForm(&u); err != nil {
		flash.Error(err.Error())
		result = false
	}
	if _, err := m.UpdateUser(&u); err != nil {
		flash.Error(err.Error())
		result = false
	}
	if result {
		flash.Success("修改成功！")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.UserList"), 302)
}

// @router /user/deluser [post]
func (r *UserController) DelUser() {
	flash := beego.NewFlash()
	result := true
	id, err := r.GetInt64("Id")
	if err != nil {
		flash.Error(err.Error())
		result = false
	}
	if id == r.GetSession("userid").(int64) && id == 1 {
		flash.Notice("当前登录用户禁止删除")
		result = false
	} else if _, err := m.DelUserById(id); err != nil {
		flash.Error(err.Error())
		result = false
	}
	if result {
		flash.Success("删除成功！")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.UserList"), 302)
}

// @router /user/getuser [get]
func (r *UserController) GetUser() {
	username := r.GetString("username")
	user := m.GetUserByUsername(username)
	r.Data["json"] = &user
	r.ServeJSON()
}

// @router /user/rolelist [get]
func (r *UserController) RoleList() {
	keyword := r.GetString("keyword")
	sort := r.GetString("sort")
	page, err := r.GetInt64("p")
	cond := orm.NewCondition()
	var cond1 *orm.Condition
	if keyword != "" {
		cond1 = cond.Or("title__contains", keyword).Or("name__contains", keyword)
	}
	if err != nil {
		page = 1
	}
	if sort == "" {
		sort = "id"
	}
	griddate, count := m.GetRolelist(page, 10, sort, cond1)
	pagination.SetPaginator(r.Ctx, 10, count)
	r.Data["griddate"] = griddate
	r.Data["search"] = keyword
	r.Data["sort"] = sort
}

// @router /user/getrole [get]
func (r *UserController) GetRole() {
	id, _ := r.GetInt64("id")
	o := orm.NewOrm()
	role := m.Role{Id: id}
	o.Read(&role)
	r.Data["json"] = &role
	r.ServeJSON()
}

// @router /user/addrole [post]
func (r *UserController) AddRole() {
	flash := beego.NewFlash()
	result := true
	u := m.Role{}
	if err := r.ParseForm(&u); err != nil {
		flash.Error(err.Error())
		result = false
	}
	if _, err := m.AddRole(&u); err != nil {
		flash.Error(err.Error())
		result = false
	}
	if result {
		flash.Success("角色添加成功！")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.RoleList"), 302)
}

// @router /user/updaterole [post]
func (r *UserController) UpdateRole() {
	flash := beego.NewFlash()
	result := true
	u := m.Role{}
	if err := r.ParseForm(&u); err != nil {
		flash.Error(err.Error())
		result = false
	}
	if _, err := m.UpdateRole(&u); err != nil {
		flash.Error(err.Error())
		result = false
	}
	if result {
		flash.Success("更新成功！")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.RoleList"), 302)
}

// @router /user/delrole [post]
func (r *UserController) DelRole() {
	flash := beego.NewFlash()
	result := true
	id, err := r.GetInt64("Id")
	if err != nil {
		flash.Error(err.Error())
		result = false
	}
	if id == 1 {
		flash.Notice("此角色禁止删除")
		result = false
	} else if _, err := m.DelRoleById(id); err != nil {
		flash.Error(err.Error())
		result = false
	}
	if result {
		flash.Success("删除成功！")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.RoleList"), 302)
}

// @router /user/useraccess [get]
func (r *UserController) UserAccess() {
	keyword := r.GetString("keyword")
	sort := r.GetString("sort")
	page, err := r.GetInt64("p")
	cond := orm.NewCondition()
	var cond1 *orm.Condition
	if keyword != "" {
		cond1 = cond.Or("title__contains", keyword).Or("name__contains", keyword)
	}
	if err != nil {
		page = 1
	}
	if sort == "" {
		sort = "id"
	}
	griddate, count := m.GetRolelist(page, 10, sort, cond1)

	//当前用户已有角色
	userid, _ := r.GetInt64("userid")
	if userid < 1 {
		userid, _ = r.GetSession("userid").(int64)
	}
	o := orm.NewOrm()
	user := m.User{Id: userid}
	o.Read(&user)
	r.Data["userinfo"] = &user
	rolelist, _ := m.GetRoleByUserId(user.Id)
	for _, item := range griddate {
		item["IsUse"] = false
		for _, role := range rolelist {
			if role["Id"] == item["Id"] {
				item["IsUse"] = true
			}
		}

	}
	pagination.SetPaginator(r.Ctx, 10, count)
	r.Data["griddate"] = griddate
	r.Data["search"] = keyword
	r.Data["sort"] = sort
}

// @router /user/addroleuser [post]
func (r *UserController) AddRoleUser() {
	flash := beego.NewFlash()
	userid, err1 := r.GetInt64("userid")
	roleid, err2 := r.GetInt64("roleid")
	if err1 == nil && err2 == nil {
		if _, err := m.AddRoleUser(roleid, userid); err != nil {
			flash.Error(err.Error())
		} else {
			flash.Success("添加成功！")
		}
	} else {
		flash.Error("参数无效")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.UserAccess", "userid", userid), 302)
}

// @router /user/delroleuser [post]
func (r *UserController) DelRoleUser() {
	flash := beego.NewFlash()
	userid, err1 := r.GetInt64("userid")
	roleid, err2 := r.GetInt64("roleid")
	if err1 == nil && err2 == nil {
		if _, err := m.DelRoleUser(roleid, userid); err != nil {
			flash.Error(err.Error())
		} else {
			flash.Success("移除成功！")
		}

	} else {
		flash.Error("参数无效")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.UserAccess", "userid", userid), 302)
}

// @router /user/roleaccess [get]
func (r *UserController) RoleAccess() {
	//当前用户已有角色
	roleid, _ := r.GetInt64("roleid")
	if roleid < 1 {
		roleid = 1
	}
	o := orm.NewOrm()
	role := m.Role{Id: roleid}
	o.Read(&role)
	r.Data["roleinfo"] = &role
	r.Data["showsearch"] = false
	nodelist, _ := m.GetNodelistByRoleId(role.Id)
	for i := 1; i < 3; i++ {
		var nodedata []orm.Params
		if i == 1 {
			nodedata, _ = m.GetNodelistByGroupid(1)
		}
		if i == 2 {
			nodedata, _ = m.GetNodelistByGroupid(2)
		}
		var firstlv []orm.Params
		for _, item := range nodedata {
			item["IsUse"] = false
			for _, nole := range nodelist {
				if nole["Id"] == item["Id"] {
					item["IsUse"] = true
				}
			}
		}
		for _, r1 := range nodedata {
			if r1["Level"].(int64) == 1 {
				var secondlv []orm.Params
				for _, r2 := range nodedata {
					if r2["Level"].(int64) == 2 && r2["Pid"].(int64) == r1["Id"].(int64) {
						secondlv = append(secondlv, r2)
					}
				}
				r1["children"] = secondlv
				firstlv = append(firstlv, r1)
			}
		}
		r.Data["nodedata"+strconv.Itoa(i)] = firstlv
	}
}

// @router /user/addrolenode [post]
func (r *UserController) AddRoleNode() {
	flash := beego.NewFlash()
	nodeid, err1 := r.GetInt64("nodeid")
	roleid, err2 := r.GetInt64("roleid")
	if err1 == nil && err2 == nil {
		if _, err := m.AddRoleNode(roleid, nodeid); err != nil {
			flash.Error(err.Error())
		} else {
			flash.Success("添加成功！")
		}
	} else {
		flash.Error("参数无效")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.RoleAccess", "roleid", roleid), 302)
}

// @router /user/delrolenode [post]
func (r *UserController) DelRoleNode() {
	flash := beego.NewFlash()
	nodeid, err1 := r.GetInt64("nodeid")
	roleid, err2 := r.GetInt64("roleid")
	if err1 == nil && err2 == nil {
		if _, err := m.DelRoleNode(roleid, nodeid); err != nil {
			flash.Error(err.Error())
		} else {
			flash.Success("移除成功！")
		}

	} else {
		flash.Error("参数无效")
	}
	flash.Store(&r.Controller)
	r.Redirect(r.URLFor("Admin.UserController.RoleAccess", "roleid", roleid), 302)
}
